package com.qiku.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义全局黑名单过滤器  对所有路由生效
 *
 * 模拟黑名单
 */
@Component
public class BlackListFilter implements GlobalFilter {
    //模拟和名单   实际上应该去redis中查询
    private static List<String> blackList = new ArrayList<>();
    @Value("${server.port}")
    private String port;
    //使用静态代码块初始化
    static {
        blackList.add("192.168.194.1");
//        blackList.add("0:0:0:0:0:0:0:1");
    }
    /**
     * 过滤器的核心方法
     * @param exchange  封装了request  和 response 对象的上下文
     * @param chain   网关过滤器链  可以控制是否放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println(">>>>>>>>当前网关端口："+port);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        InetSocketAddress ipClient = request.getRemoteAddress();
        System.out.println("客户端ip："+ipClient.getHostString());
        //判断黑名单中是否包含客户端ip
        if (blackList.contains(ipClient.getHostString())){
            //包含>>>>>拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);  //状态码
            System.out.println("黑名单成员,无权访问~");
            //准备响应信息
            String data = "Request be denied";
            //将信息进一步封装
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        } else {
            //不包含>>>>放行
            return chain.filter(exchange);
        }
    }
}
